import EventEmitter from './EventEmitter';

// 这个事件模型 好像没有那么准确
// 生产者消费者的模型会不会更好一点？
// 主要是state变更的时候一定要消费掉他，事件模型可能会存在没有监听到的情况
class StateBridge {
    constructor() {
        this.bridge = new EventEmitter();
        this.pendingDom = {};
        this.stateBuffer = {};
    }
    onDomReady(elementId, callback) {
        const uniqueEventName = `domReady.${elementId}`;
        if (this.bridge.events[uniqueEventName]) {
            console.error(`the elementId should be unique,but found other same `, uniqueEventName)
        }
        // 防止内存泄漏
        const clearDom = () => {
            this.pendingDom[elementId] = null;
        }
        if (this.pendingDom[elementId]) {
            callback(this.pendingDom[elementId]);
            return this.bridge.on(`domReady.${elementId}`, clearDom);
        }
        return this.bridge.on(`domReady.${elementId}`, (element) => {
            callback(element);
            clearDom();
        });
    }
    emitDomReady(elementId, element) {
        this.pendingDom[elementId] = element;
        this.bridge.emit(`domReady.${elementId}`, element);
    }
    produceState(stateId, obj) {
        if (typeof obj !== 'object' || Array.isArray(obj)) {
            console.error('state should be a object');
            return;
        }
        this.stateBuffer = (this.stateBuffer[stateId] || []).push(obj);
        this.bridge.emit(`stateChange.${stateId}`, obj);
    }
    consumeState(stateId, callback) {
        if (this.stateBuffer[stateId] && this.stateBuffer[stateId].length > 0) {
            callback(this.stateBuffer[stateId].pop());
            this.stateBuffer[stateId] = [];
        }
        return this.bridge.on(`stateChange.${stateId}`, () => {
            const changedState = this.stateBuffer[stateId].pop();
            if (changedState) callback(changedState);
            this.stateBuffer[stateId] = [];
        });
    }
}

export default new StateBridge();